<template>
  <a-layout>
    <div class="manage-slide pt24 pr24">
      <a-layout>
        <a-layout-sider :width="240" style="height: calc(100vh - 112px); overflow: auto; background-color: #fff">
          <div class="manage-slide-title" @mouseenter="addIcon = true" @mouseleave="addIcon = false">
            全部合同({{ categorieslistAllNum }})
            <a-icon class="mg_l74" type="form" @click="onJumpGroup" />
          </div>
          <a-menu class="manage-slide-groupleft" ref="antMenu" v-model="key">
            <a-menu-item v-for="item in groupList" :key="item.id" style="padding: 0 0 0 24px" @click="getCategorieslistAll(item.id)">
              <a-row type="flex" align="middle" justify="space-between" style="border-bottom: 1px solid #e8e8e8">
                <a-tooltip placement="top">
                  <template slot="title">
                    <span>{{ item.name }}</span>
                  </template>
                  <div class="groupname">
                    <div class="ellipsis" style="float: left; max-width: 140px">
                      {{ item.name }}
                    </div>
                    <div style="float: left">({{ item.categoryCount }})</div>
                  </div>
                </a-tooltip>
                <a-col>
                  <a-icon v-if="act == item.id" type="setting" @click.stop="setting(item)" />
                </a-col>
              </a-row>
            </a-menu-item>
          </a-menu>
        </a-layout-sider>
        <a-layout>
          <a-row type="flex" class="lay-head">
            <a-input-search placeholder="搜索合同模板" style="width: 200px" v-model="searchName" @search="onSearch" :allowClear="true" />
            <div style="display: flex">
              <a-button v-if="isContainByString('contractAdmin')" type="primary" @click="showIssueModa" style="margin-right: 10px">
                下发合同模板
              </a-button>
              <a-button type="primary" icon="plus" @click="addVisible = true"> 新增合同模板 </a-button>
            </div>
          </a-row>
          <!-- 合同类型列表 -->
          <div class="listbox" v-if="!!categorieslistAll.length">
            <div v-for="(item, index) in categorieslistAll" :key="index" class="list-item">
              <div class="list-item-col" :class="!item.fileType ? 'list-item-col-flex' : ''">
                <a-tooltip placement="top">
                  <template slot="title">
                    <span>{{ item.name }}</span>
                  </template>
                  <div class="title overflows mt4" :style="!item.fileType ? 'margin-bottom: 0;' : ''">
                    {{ item.name }}
                  </div>
                </a-tooltip>
                <a-tooltip placement="bottom" v-if="item.fileType">
                  <template slot="title">
                    <span>{{ enumerateJson[item.fileType] }}</span>
                  </template>
                  <div class="description overflows">
                    {{ enumerateJson[item.fileType] }}
                  </div>
                </a-tooltip>
              </div>
              <div class="list-item-col col2">
                <div v-if="item.signType == 'person_only'" style="display: flex; align-items: center; height: 100%">
                  <div class="title overflows mt4" style="margin-bottom: 0">员工单方签署</div>
                </div>
                <div v-else>
                  <div class="title overflows mt4">
                    {{ item.signType == "enterprise_only" ? "企业单方签署" : "企业-员工双方签署" }}
                  </div>
                  <a-tooltip placement="top" v-if="item.sealVO != null">
                    <template slot="title">
                      <span>{{ item.sealVO.name }}</span>
                    </template>
                    <div class="description2 overflows">
                      {{ item.sealVO.name }}
                    </div>
                  </a-tooltip>
                  <a @click="setType(item)" v-else>
                    <a-icon type="plus" />
                    选择印章
                  </a>
                </div>
              </div>
              <div class="list-item-col col3">
                <div v-if="!isContainByString('contractAdmin')">
                  <a-button @click="selectebatchSign(item)">发起签署</a-button>
                </div>
                <actionPoint>
                  <li @click="setType(item)">编辑</li>
                  <li @click="onPreview(item)">预览</li>
                  <li @click="deleteType(item)">删除</li>
                </actionPoint>
              </div>
            </div>
          </div>
          <a-empty style="margin-top: 150px" v-else />
        </a-layout>
      </a-layout>
      <!-- 新增合同类型 -->
      <add :visible.sync="addVisible" :isLoadingGroup="isLoadingGroup" @confirmAddType="confirmAddType" />
      <a-modal
        :visible="issueModalVisible"
        title="下发合同模版"
        width="538px"
        :destroyOnClose="true"
        @ok="confirmIssueModal"
        @cancel="handleCancelIssueModal"
      >
        <a-row>
          <a-col :span="12">
            <span>请选择合同模板</span>
            <a-tree-select
              style="width: 240px; margin-top: 10px; max-height: 350px; overflow-y: auto"
              :tree-data="contractData"
              tree-checkable
              :replaceFields="replaceFields"
              show-search
              treeNodeFilterProp="title"
              search-placeholder="请选择合同模板"
              @change="treeSelectChange"
            />
            <a-checkbox class="mt8" v-model="isSeal"> 是否同步下发合同印章 </a-checkbox>
          </a-col>
          <a-col :span="12">
            <span>请选择下发用工单位</span>
            <a-tree-select
              :value="companyList"
              :treeData="dataList"
              :filterTreeNode="filterTreeNode"
              treeCheckable
              placeholder="请选择用工单位"
              style="width: 240px; margin-top: 10px; max-height: 350px; overflow: auto"
              @change="companySelectChange"
            />
          </a-col>
        </a-row>
      </a-modal>
      <a-modal :width="780" :visible="errVisible" title="下发结果" @cancel="errVisible = false" :footer="false">
        <a-alert
          :message="
            '本次下发' +
            allList.length +
            '个用工单位，' +
            (allList.length - errList.length) +
            '个成功，' +
            errList.length +
            '个失败，请修改问题后重新下发'
          "
          banner
        />
        <a-table style="margin-top: 24px" :columns="errColumns" :pagination="false" :data-source="errList">
          <template slot="companyName" slot-scope="text">
            <span>{{ text }}</span>
          </template>
          <template slot="failCategoryStr" slot-scope="text">
            <a-tooltip>
              <template slot="title">
                {{ text }}
              </template>
              <div style="width: 160px; text-overflow: ellipsis; white-space: nowrap; overflow: hidden">
                {{ text }}
              </div>
            </a-tooltip>
          </template>
          <template slot="reason">
            <span>用工单位内存在同名的电子合同，且处于未签署完成阶段</span>
          </template>
        </a-table>
      </a-modal>
    </div>
    <preview :visible="visible" :templateId="templateId" @close="visible = false" />
  </a-layout>
</template>

<script>
import actionPoint from "./components/actionPoint";
import add from "./components/add";
import preview from "../editSealNew/preview";
import {
  getContractGroups,
  getCategorieslistAll,
  batchDelCategories,
  findCompanyGroup,
  templateListAllReq,
  selectCompanyCount
} from "@/api/company/contract";
import { TreeSelect } from "ant-design-vue";
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
import { isContainByString } from "@/utils/index";
import { saveIssuedCategory, selectTreeBySubjectId, checkTemplateByCategoryIdReq } from "../api";
import { formatCompanyTree, formatCompanyIdNameDict } from "@/utils/tools";
const errColumns = [
  {
    title: "用工单位名称",
    dataIndex: "companyName",
    scopedSlots: { customRender: "companyName" },
    ellipsis: true,
    width: 180
  },
  {
    title: "合同模板名称",
    dataIndex: "failCategoryStr",
    scopedSlots: { customRender: "failCategoryStr" },
    ellipsis: true,
    width: 180
  },
  {
    title: "错误信息",
    dataIndex: "reason",
    scopedSlots: { customRender: "reason" },
    ellipsis: true,
    width: 395
  }
];
export default {
  components: {
    actionPoint,
    add,
    preview
  },
  data() {
    return {
      isLoadingGroup: false,
      errColumns,
      addVisible: false,
      SHOW_PARENT,
      issueModalVisible: false,
      isContainByString,
      errList: [],
      errVisible: false,
      // 添加图标
      addIcon: false,
      // 设置图标
      act: false,
      companyId: this.$store.state.hr.companyId,
      groupList: [],
      dataList: [],
      dataListDict: {},
      key: null,
      categorieslistAll: [],
      defaultLeaveList: [],
      categorieslistAllNum: 0,
      // 下发选择框合同数据
      contractData: [],
      // 已选的合同模板数据
      contractList: [],
      // 已选的公司数据
      companyList: [],
      replaceFields: {
        children: "categoryListVOList",
        key: "id",
        value: "id",
        title: "name"
      },
      tableLoading: false,
      fromLeave: false,
      categoryNameList: [],
      allList: [],
      templateId: 0,
      visible: false,
      isSeal: false,
      enumerateJson: {
        laborContractLimit: "固定期限劳动合同",
        laborContractUnlimit: "无固定期限劳动合同",
        laborContractJobs: "以完成一定工作任务为期限的劳动合同",
        internAccords: "实习协议",
        laborContract: "劳务合同",
        reemployAccords: "返聘协议",
        laborContractDispatch: "劳务派遣合同",
        borrowedContract: "借调合同",
        engagementLetter: "约定书",
        partTime: "兼职合同",
        noviciateAgreement: "见习协议",
        dimissionContract: "离职合同",
        retireReEmploy: "退休返聘合同",
        other: "其它"
      },
      searchName: "",
      groupId: "",
      contractSum: 0,
      contractCount: 0,
      faceSum: 0,
      faceCount: 0
    };
  },
  created() {
    this.onGetContractGroups();
    if (this.$route.query.fromLeave) {
      this.fromLeave = this.$route.query.fromLeave;
    }
    if (this.$route.query.leaveList) {
      this.defaultLeaveList = this.$route.query.leaveList;
    }
    this.findCompanyGroup();
  },
  mounted() {
    this.selectTreeBySubjectId();
    const st = this.$route.query.operateFromShortcut;
    if (st === "chuangjianhetongmuban") {
      this.addVisible = true;
    }
  },
  methods: {
    filterTreeNode(inVal, node) {
      if (node.data.props.title.toLowerCase().indexOf(inVal.toLowerCase()) >= 0) {
        return true;
      }
      return false;
    },
    companySelectChange(companyKeys) {
      this.companyList = companyKeys.filter((item) => item.includes("_company_"));
    },
    getName(name) {
      return name;
    },
    treeSearch2(e) {
      this.selectTreeBySubjectId(e);
    },
    treeSearch(e) {
      this.findCompanyGroup(e);
    },
    findCompanyGroup(e) {
      findCompanyGroup({ name: e || null })
        .then((res) => {
          this.dataList = formatCompanyTree(res.data);
          this.dataListDict = formatCompanyIdNameDict(res.data);
          this.companyList = JSON.parse(JSON.stringify(this.companyList));
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    // 获取分组列表
    onGetContractGroups() {
      this.key = null;
      this.tableLoading = true;
      if (this.isLoadingGroup) {
        return false;
      }
      this.isLoadingGroup = true;
      getContractGroups({
        subjectId: this.isContainByString("contractAdmin") ? "0" : this.companyId
      })
        .then((res) => {
          this.isLoadingGroup = false;
          this.tableLoading = false;
          this.groupList = res.data;
          this.groupList.forEach((e, i) => {
            e.index = i;
            this.categorieslistAllNum += e.categoryCount;
          });
          this.key = [res.data[0].id];
          this.groupId = [res.data[0].id];
          this.getCategorieslistAll();
        })
        .catch((err) => {
          this.isLoadingGroup = false;
          console.log(err);
        });
    },
    // 获取分组下的合同类型列表
    getCategorieslistAll(id) {
      if (id) this.groupId = id;
      getCategorieslistAll({
        name: this.searchName,
        groupId: this.groupId,
        valid: true,
        subjectId: this.isContainByString("contractAdmin") ? "0" : this.companyId
      }).then((res) => {
        this.categorieslistAll = res.data;
      });
    },
    deleteType(item) {
      this.$confirm({
        title: "提示",
        content: `确定删除类型 ${item.name} 吗？`,
        okText: "确认",
        cancelText: "取消",
        onOk: () => {
          batchDelCategories([item.id]).then(() => {
            this.$message.success("删除成功");
            this.onGetContractGroups();
            this.selectTreeBySubjectId();
          });
        }
      });
    },
    /* 搜索 */
    onSearch() {
      this.getCategorieslistAll();
    },
    // 设置
    setType(item) {
      sessionStorage.setItem("contractTypeQueryName", item.name);
      sessionStorage.setItem("editSealNewStatus", 0);
      sessionStorage.setItem("categoryUpdateDTO", "{}");
      sessionStorage.setItem("signedsStatus", "");
      this.$router.push({
        name: this.isContainByString("contractAdmin") ? "settingAdmin" : "setting",
        // name: "settingAdmin",
        query: {
          id: item.id,
          groupId: item.groupId
        }
      });
    },
    // TODO上传文件发起签署（隐藏）
    toSignTemplate() {
      // 跳转模板加盖印章
    },
    selectebatchSign(item) {
      checkTemplateByCategoryIdReq(item.id)
        .then((res) => {
          if (item.signType !== "person_only") {
            if (item.enterpriseSealId != null) {
              if (item.signType === "enterprise_only") {
                // 企业单方签署
                this.$router.push({
                  name: this.isContainByString("contractAdmin") ? "initiateSignAdmin" : "initiateSign",
                  query: {
                    id: item.id,
                    sign: "enterpriseonly",
                    leaveList: this.defaultLeaveList,
                    fromLeave: this.fromLeave
                  }
                });
              } else {
                this.$router.push({
                  name: this.isContainByString("contractAdmin") ? "initiateSignAdmin" : "initiateSign",
                  query: {
                    id: item.id,
                    leaveList: this.defaultLeaveList,
                    fromLeave: this.fromLeave
                  }
                });
              }
            } else {
              this.$message.warning("请前往该模板设置加盖印章");
            }
          } else {
            this.$router.push({
              name: this.isContainByString("contractAdmin") ? "initiateSignAdmin" : "initiateSign",
              query: {
                id: item.id,
                leaveList: this.defaultLeaveList,
                fromLeave: this.fromLeave
              }
            });
          }
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },
    // 下发接口
    saveIssuedCategory() {
      if (this.companyList.length === 0) {
        this.$notification["error"]({
          message: "错误",
          description: "请选择需要下发的公司"
        });
        return;
      }
      if (this.contractList.length === 0) {
        this.$notification["error"]({
          message: "错误",
          description: "请选择需要下发的合同模板"
        });
        return;
      }
      const companyArr = Array.from(new Set(this.companyList.map((item) => item.split("_")[2])));
      const data = {
        subjectList: companyArr.map((id) => ({
          subjectId: id,
          subjectName: this.dataListDict[id]
        })),
        categoryList: this.contractList,
        isSeal: this.isSeal
      };
      saveIssuedCategory(data)
        .then((res) => {
          this.issueModalVisible = false;
          this.$notification["success"]({
            message: "成功",
            description: "下发成功"
          });
          this.companyList = [];
          this.errList = [];
          this.allList = res.data || [];
          var num = 0;
          res.data.forEach((item) => {
            if (item.failCategoryList.length > 0) {
              item.failCategoryStr = item.failCategoryList.join(",");
              num++;
              this.errList.push(item);
            }
          });
          if (num > 0) {
            this.errVisible = true;
          }
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },

    // 查询合同树状结构
    selectTreeBySubjectId(e) {
      selectTreeBySubjectId({
        name: e || null,
        subjectId: this.isContainByString("contractAdmin") ? "0" : this.companyId
      })
        .then((res) => {
          this.contractData = res.data;
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    treeSelectChange(value, label, extra) {
      this.contractList = [];
      this.categoryNameList = [];
      this.contractData.forEach((item) => {
        const categoryListVOList = item.categoryListVOList;
        if (categoryListVOList && categoryListVOList.length > 0) {
          const itemObj = { contractGroupName: item.name, categoryIds: [] };
          item.categoryListVOList.forEach((itemItem) => {
            if (value.indexOf(itemItem.id) !== -1) {
              itemObj.categoryIds.push(itemItem.id);
            }
          });
          if (itemObj.categoryIds.length > 0) {
            this.contractList.push(itemObj);
          }
        }
      });
    },

    confirmIssueModal() {
      // TODO 下发接口
      this.saveIssuedCategory();
    },
    handleCancelIssueModal() {
      this.issueModalVisible = false;
      // 已选的合同模板数据
      this.contractList = [];
      // 已选的公司数据
      this.companyList = [];
    },
    showIssueModa() {
      this.issueModalVisible = true;
      this.isSeal = false;
    },
    confirmAddType() {
      this.onGetContractGroups();
      this.selectTreeBySubjectId();
    },
    onPreview(e) {
      this.getTemplateListAllReq(e.id);
    },
    async getTemplateListAllReq(id) {
      try {
        const { data } = await templateListAllReq(id);
        this.templateId = data[0].id;
        this.visible = true;
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    onJumpGroup() {
      const path = this.isContainByString("contractAdmin") ? "/contractAdmin/group" : "/contract/group";
      this.$router.push({ path, query: {} });
    }
  }
};
</script>
<style lang="scss">
.slide {
  .ant-layout-sider-children {
    border-right: 1px solid #e8e8e8;
  }
}
</style>
<style lang="scss" scoped>
.fix-item-wrapper2 {
  width: 40%;
  display: flex;
  height: 120px;
  background: #ffffff;
  border-radius: 8px;
  margin-top: 25px;
  margin-left: 25px;
  margin-right: 25px;
  padding: 33px;
  border: 1px solid #e8e8e8;

  .remainderQuotaName {
    font-size: 14px;
    font-weight: 300;
    color: #9c9c9c;
  }

  .remainderQuota {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    font-weight: 500;
    color: #333333;
  }

  .fix-item-two {
    padding-left: 23px;
    margin-top: 10px;
    width: 50%;
    height: 45px;
    padding-right: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.manage-slide {
  .lay-head {
    width: 100%;
    padding: 0 0 24px 24px;
    display: flex;
    justify-content: space-between;
  }
  .manage-slide-title {
    height: 48px;
    line-height: 48px;
    font-size: 16px;
    font-weight: 500;
    color: rgba(0, 0, 0, 1);
    padding-left: 24px;
    cursor: pointer;
  }
  ::v-deep.ant-menu-inline,
  .ant-menu-vertical,
  .ant-menu-vertical-left {
    border-right: none !important;
  }

  .groupname {
    width: 100%;
    height: 40px;
    border-bottom: 1px solid #e8e8e8;
  }
  .listbox {
    max-height: calc(100vh - 220px);
    overflow: auto;
    margin-left: 20px;
    padding: 6px;
    .list-item {
      width: 100%;
      height: 118px;
      background: #ffffff;
      border: 1px solid #e8e8e8;
      border-radius: 4px;
      padding: 24px;
      margin-bottom: 24px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      &:hover {
        border: 0;
        box-shadow: 0px 4px 12px 0px rgba(106, 102, 246, 0.1);
      }
      .overflows {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .list-item-col-flex {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
      }
      .list-item-col {
        width: 32%;
        height: 100%;
        border-right: 1px solid #e5e5e5;
        &:last-child {
          border: 0;
        }
        .title {
          width: 90%;
          font-size: 16px;
          font-weight: 500;
          color: #3c3d43;
          margin-bottom: 14px;
        }
        .description {
          width: 90%;
          font-weight: 400;
          color: #a6a8b4;
        }
        .description2 {
          width: 90%;
          font-weight: 400;
          color: #767885;
        }
      }
      .col2 {
        padding-left: 32px;
      }
      .col3 {
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    .listItem {
      width: 50%;

      .listbtm {
        button {
          padding: 0;
        }
      }
    }
    .setline {
      width: 50%;
      display: flex;
      border-left: 1px solid #e8e8e8;
      align-items: flex-start;
      justify-content: flex-end;
      ::v-deep.ant-select-selection__placeholder,
      ::v-deep.ant-select-search__field__placeholder {
        color: #000;
      }
    }
  }
  .manage-slide-groupleft {
    width: 100%;
    max-height: 580px;
    overflow: auto;
  }
}
</style>
